package com.zy.adapter.product;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import zy.dto.base.product.ProductCartDto;
import zy.entity.base.bra.T_Base_Bra;
import zy.entity.base.color.T_Base_Color;
import zy.entity.base.size.T_Base_Size;
import zy.entity.stock.data.T_Stock_DataView;
import zy.entity.vip.member.T_Vip_Member;
import zy.util.StringUtil;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.android.volley.toolbox.ImageLoader.ImageContainer;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.zy.R;
import com.zy.activity.product.ProductActivity;
import com.zy.util.ActivityUtil;
import com.zy.util.BitmapCache;
import com.zy.util.CommonParam;
import com.zy.util.ImageUtil;
import com.zy.view.view.RadioGroupView;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

public class ProductAdapter extends BaseAdapter{
	private Context context;
	private List<ProductCartDto> productCartDtos = new ArrayList<ProductCartDto>();
	private T_Vip_Member member;
	private LayoutInflater listContainer; 
	private ImageLoader imageLoader;
	private String cr_code,sz_code,br_code;
	
	public ProductAdapter(Context context,List<ProductCartDto> productCartDtos,T_Vip_Member member) {
		this.context = context;
		this.productCartDtos = productCartDtos;
		this.member = member;
		listContainer = LayoutInflater.from(context);
		imageLoader = new ImageLoader(Volley.newRequestQueue(context), new BitmapCache());
	}
	
	@Override
	public int getCount() {
		return productCartDtos.size();
	}

	@Override
	public Object getItem(int position) {
		return productCartDtos.get(position);
	}

	@Override
	public long getItemId(int position) {
		return productCartDtos.get(position).getPd_id();
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		// 自定义视图
		final ListItemView listItemView;
		if (convertView == null) {
			listItemView = new ListItemView();
			convertView = listContainer.inflate(R.layout.layout_product_item,null);
			listItemView.iv_product_img = (ImageView) convertView.findViewById(R.id.iv_product_img);
			listItemView.tv_pd_no = (TextView) convertView.findViewById(R.id.tv_pd_no);
			listItemView.tv_pd_name = (TextView) convertView.findViewById(R.id.tv_pd_name);
			listItemView.tv_brand_type = (TextView) convertView.findViewById(R.id.tv_brand_type);
			listItemView.tv_sell_price = (TextView) convertView.findViewById(R.id.tv_sell_price);
			listItemView.tv_add_cart = (TextView) convertView.findViewById(R.id.tv_add_cart);
			listItemView.tv_try = (TextView) convertView.findViewById(R.id.tv_try);
			listItemView.tv_try_split = (TextView) convertView.findViewById(R.id.tv_try_split);
			listItemView.ll_detail_info = (LinearLayout) convertView.findViewById(R.id.ll_detail_info);
			listItemView.rgv_color = (RadioGroupView) convertView.findViewById(R.id.rgv_color);
			listItemView.rgv_size = (RadioGroupView) convertView.findViewById(R.id.rgv_size);
			listItemView.tv_minus = (TextView) convertView.findViewById(R.id.tv_minus);
			listItemView.tv_amount = (TextView) convertView.findViewById(R.id.tv_amount);
			listItemView.tv_add = (TextView) convertView.findViewById(R.id.tv_add);
			listItemView.btn_add_cart = (Button) convertView.findViewById(R.id.btn_add_cart);
			listItemView.btn_try = (Button) convertView.findViewById(R.id.btn_try);
			convertView.setTag(listItemView);
		} else {
			listItemView = (ListItemView) convertView.getTag();
		}
		if (null != productCartDtos && productCartDtos.size() > 0) {
			if(member == null){
				listItemView.tv_try.setVisibility(View.GONE);
				listItemView.tv_try_split.setVisibility(View.GONE);
				listItemView.btn_try.setVisibility(View.GONE);
			}
			final ProductCartDto item = productCartDtos.get(position);
			listItemView.tv_pd_no.setText(StringUtil.trimString(item.getPd_no()));
			listItemView.tv_pd_name.setText(StringUtil.trimString(item.getPd_name()));
			listItemView.tv_brand_type.setText(StringUtil.trimString(item.getPd_tp_name())+"/"+StringUtil.trimString(item.getPd_bd_name())+" "+StringUtil.trimString(item.getPd_style()));
			listItemView.tv_sell_price.setText("零售价：￥"+String.format("%.2f", item.getPd_sell_price()));
			if(StringUtil.isNotEmpty(item.getPdm_img_path())){
				loadBitmap(CommonParam.file_url+item.getPdm_img_path(), listItemView.iv_product_img);
			}else {
				listItemView.iv_product_img.setImageResource(R.drawable.nophoto);
			}
			if(item.isSelected()){
				listItemView.ll_detail_info.setVisibility(View.VISIBLE);
				if(item.getStockMap() != null){
					initStockData(listItemView.rgv_color,listItemView.rgv_size, item);
				}
			}else {
				listItemView.ll_detail_info.setVisibility(View.GONE);
			}
			listItemView.tv_add_cart.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					cr_code = "";
					br_code = "";
					sz_code = "";
					for (int i = 0; i < productCartDtos.size(); i++) {
						productCartDtos.get(i).setSelected(false);
					}
					productCartDtos.get(position).setSelected(true);
					notifyDataSetChanged();
					if(productCartDtos.get(position).getStockMap() == null){//查询库存信息
						((ProductActivity)context).loadStockData(position);
					}
				}
			});
			listItemView.tv_try.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					cr_code = "";
					br_code = "";
					sz_code = "";
					for (int i = 0; i < productCartDtos.size(); i++) {
						productCartDtos.get(i).setSelected(false);
					}
					productCartDtos.get(position).setSelected(true);
					notifyDataSetChanged();
					if(productCartDtos.get(position).getStockMap() == null){//查询库存信息
						((ProductActivity)context).loadStockData(position);
					}
				}
			});
			listItemView.tv_minus.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					if(item.getAmount() <= 1){
						ActivityUtil.showShortToast(context, "购买数量必须大于0");
						return;
					}
					item.setAmount(item.getAmount() - 1);
					listItemView.tv_amount.setText(String.valueOf(item.getAmount()));
				}
			});
			listItemView.tv_add.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					item.setAmount(item.getAmount() + 1);
					listItemView.tv_amount.setText(String.valueOf(item.getAmount()));
				}
			});
			listItemView.btn_add_cart.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					if (StringUtil.isEmpty(cr_code) || StringUtil.isEmpty(sz_code)) {
						ActivityUtil.showShortToast(context, "请选择颜色尺码");
						return;
					}
					((ProductActivity)context).saveCartList(position,cr_code,sz_code,br_code);
				}
			});
			listItemView.btn_try.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					if (StringUtil.isEmpty(cr_code) || StringUtil.isEmpty(sz_code)) {
						ActivityUtil.showShortToast(context, "请选择颜色尺码");
						return;
					}
					((ProductActivity)context).saveTryList(position, cr_code, sz_code, br_code);
				}
			});
		}
		return convertView;
	}
	
	private void initStockData(RadioGroupView rgv_color,RadioGroupView rgv_size,ProductCartDto productCartDto){
		rgv_color.removeAllViews();
		List<T_Base_Color> colorList = (List<T_Base_Color>)productCartDto.getStockMap().get("color");
		if(null != colorList && colorList.size() > 0){
			int index = 0;
			cr_code = colorList.get(0).getCr_code();
			for (T_Base_Color color : colorList) {
				int amount = getColorStock(productCartDto.getStockMap(),productCartDto.getPd_code(),color.getCr_code());
				RadioButton btn = initColor(rgv_color,rgv_size,color, amount,productCartDto);
				if(index == 0){
					btn.performClick();
				}
				index ++;
			}
		}
	}
	private int getColorStock(Map<String, Object> stockMap,String pd_code,String cr_code){
		int amount = 0;
		List<T_Stock_DataView> stocks = (List<T_Stock_DataView>)stockMap.get("stocks");
		for (T_Stock_DataView stock:stocks) {
			if (stock.getSd_code().startsWith(pd_code + cr_code)) {
				amount += stock.getSd_amount();
			}
		}
		return amount;
	}
	private int getSizeStock(Map<String, Object> stockMap,String pd_code,String cr_code,String sizeCode){
		List<T_Stock_DataView> stocks = (List<T_Stock_DataView>)stockMap.get("stocks");
		String subCode = pd_code + StringUtil.trimString(cr_code)+StringUtil.trimString(sizeCode);
		for (T_Stock_DataView data:stocks) {
			if (subCode.equals(data.getSd_code())){
				return data.getSd_amount();
			}
		}
		return 0;
	}
	private RadioButton initColor(RadioGroupView rgv_color,final RadioGroupView rgv_size,final T_Base_Color color,final int amount,
			final ProductCartDto productCartDto){
		RadioButton btn = new RadioButton(rgv_color.getContext());
		setRadioStyle(btn);
		btn.setText(color.getCr_name()+"["+amount+"]");
		btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				cr_code = color.getCr_code();
				sz_code = "";
				br_code = "";
				initSize(rgv_size,color.getCr_code(), productCartDto);
			}
		});
		rgv_color.addView(btn);
		return btn;
	}
	private void setRadioStyle(RadioButton btn){
		btn.setTextColor(Color.BLACK);
		btn.setButtonDrawable(android.R.color.transparent);
		btn.setBackgroundResource(R.drawable.radio_bg);
		btn.setPadding(25, 15, 25, 15);
	}
	
	private RadioButton addSizeControl(RadioGroupView rgv_size,final T_Base_Size size,final T_Base_Bra bra,int stock){
		StringBuffer text = new StringBuffer();
		text.append(size.getSz_name());
		if(bra != null){
			text.append("/").append(bra.getBr_name());
		}
		text.append("[").append(stock).append("]");
		
		RadioButton btn = new RadioButton(rgv_size.getContext());
		setRadioStyle(btn);
		btn.setText(text);		
		btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				sz_code = size.getSz_code();
				if(bra != null){
					br_code = bra.getBr_code();
				}else {
					br_code = "";
				}
			}
		});
		rgv_size.addView(btn);
		return btn;
	}
	
	private void initSize(RadioGroupView rgv_size,String cr_code,ProductCartDto productCartDto){
		rgv_size.removeAllViews();
		List<T_Base_Size> sizes = (List<T_Base_Size>)productCartDto.getStockMap().get("size");
		List<T_Base_Bra> bras = (List<T_Base_Bra>)productCartDto.getStockMap().get("bra");
		int index = 0;
		for (T_Base_Size size : sizes) {
			if (null != bras && bras.size() > 0) {
				for (T_Base_Bra bra : bras) {
					int stock = getSizeStock(productCartDto.getStockMap(),productCartDto.getPd_code(), cr_code,size.getSz_code() + bra.getBr_code());
					if (stock == 0) {
						continue;
					}
					RadioButton btn = addSizeControl(rgv_size, size, bra, stock);
					if (index == 0) {
						btn.performClick();
					}
					index++;
				}
			} else {
				int stock = getSizeStock(productCartDto.getStockMap(), productCartDto.getPd_code(), cr_code, size.getSz_code());
				if (stock == 0) {
					continue;
				}
				RadioButton btn = addSizeControl(rgv_size, size, null, stock);
				if (index == 0) {
					btn.performClick();
				}
				index++;
			}
		}
	}
	
	public final class ListItemView { // 自定义控件集合
		public ImageView iv_product_img;
		public TextView tv_pd_no, tv_pd_name,tv_brand_type,tv_sell_price,tv_add_cart,tv_try,tv_try_split;
		public LinearLayout ll_detail_info;
		public RadioGroupView rgv_color,rgv_size;
		public TextView tv_minus,tv_amount,tv_add;
		public Button btn_add_cart,btn_try;
	}
	private void loadBitmap(String url,final ImageView imageView){
		imageLoader.get(url, new ImageListener() {
			@Override
			public void onResponse(ImageContainer response, boolean isImmediate) {
				Bitmap bitmap = response.getBitmap();
				if(bitmap != null){
					imageView.setImageBitmap(ImageUtil.getCircleBitmap(bitmap));
				}
			}
			@Override
			public void onErrorResponse(VolleyError arg0) {
				
			}
		});
	}
}
